package com.example.distillapplication.ui.fragment.base;

import android.content.Context;
import android.os.Bundle;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import com.example.distillapplication.App;
import com.example.distillapplication.data.viewmodel.DataBaseViewModel;
import com.example.distillapplication.data.viewmodel.InstrumentStateViewModel;
import com.example.distillapplication.data.viewmodel.SerialMessageViewModel;
import com.example.distillapplication.data.viewmodel.SharedViewModel;

public class BaseFragment extends Fragment {
    protected AppCompatActivity mActivity;
    protected SharedViewModel mSharedViewModel;
    protected DataBaseViewModel mDataBaseViewModel;
    protected InstrumentStateViewModel mInstrumentStateViewModel;
    protected SerialMessageViewModel mSerialMessageViewModel;

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        mActivity = (AppCompatActivity) context;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mSharedViewModel = getAppViewModelProvider().get(SharedViewModel.class);
        mDataBaseViewModel = getAppViewModelProvider().get(DataBaseViewModel.class);
        mInstrumentStateViewModel = getAppViewModelProvider().get(InstrumentStateViewModel.class);
        mSerialMessageViewModel = getAppViewModelProvider().get(SerialMessageViewModel.class);
    }

    public void showLongToast(String text) {
        Toast.makeText(mActivity.getApplicationContext(), text, Toast.LENGTH_LONG).show();
    }

    public void showShortToast(String text) {
        Toast.makeText(mActivity.getApplicationContext(), text, Toast.LENGTH_SHORT).show();
    }

    public void showLongToast(int stringRes) {
        showLongToast(mActivity.getApplicationContext().getString(stringRes));
    }

    public void showShortToast(int stringRes) {
        showShortToast(mActivity.getApplicationContext().getString(stringRes));
    }

    protected ViewModelProvider getAppViewModelProvider() {
        return ((App) mActivity.getApplicationContext()).getAppViewModelProvider(mActivity);
    }

    protected ViewModelProvider getFragmentViewModelProvider(Fragment fragment) {
        return new ViewModelProvider(fragment, fragment.getDefaultViewModelProviderFactory());
    }

    protected ViewModelProvider getActivityViewModelProvider(AppCompatActivity activity) {
        return new ViewModelProvider(activity, activity.getDefaultViewModelProviderFactory());
    }

    public SharedViewModel getSharedViewModel() {
        return mSharedViewModel;
    }
}
